// pages/confirmOrder/confirmOrder.js
import { $wuxDialog } from '../../components/wux/index'
import { NP } from '../../utils/util'
import orderApi from '../../service/orderApi'
import deliveryApi from '../../service/deliveryApi'
import couponApi from '../../service/couponApi'

let iptNumberComponent // 数字输入框组件实例
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderInfo: {
            name: '',
            buyNowImg: '',
            price: '',
            goodsId: '',
            quantity: '1',
            selectedTxt: '',
            stock: '9999',
            expressFee: '0.00',
            goodsType: '' // 提货类型
        },
        goodsType: '', // 提货类型
        orderId: '', // 订单ID
        deliveryAddressId: '', // 收货地址ID
        deliveryInfo: {
            userName: "",
            detailAddress: "",
            telephone: ""
        }, // 收货地址
        page: {
            start: 1,
            size: 1
        },
        totalMoney: '',
        shouldPayMoney: '',
        timerOut: null, // 定时器
        timeOutLimit: 0, // 定时器计数
        haveAddress: false, // 是否有收货地址
        onCancelTip: '', // 点击暂不提货按钮提示
        updateAddress: '1', // 是否修改收货地址
        noAvailableFlag: false, // 是否暂无可用
        dontChoose: false, // 是否不选择优惠券
        couponContent: '', // 优惠券内容
        couponInfo: {
            userCouponId: '', // 用户优惠券ID
            couponName: '', // 优惠券名称
            couponType: '', // 类型
            couponPic: '', // 图片
            describe: '', // 描述
            validTime: '', // 有效时间
            discountPrice: '',
            deductibleAmount: ''
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let that = this
        iptNumberComponent = this.selectComponent('#ipt-quantity') // 获取数字输入框实例
        let price = (app.globalData.orderInfo.price - 0).toFixed(2)
        let expressFee = (app.globalData.orderInfo.expressFee - 0).toFixed(2)
        this.setData({
            orderInfo: {...app.globalData.orderInfo },
            goodsType: app.globalData.orderInfo.goodsType,
            ['orderInfo.price']: price,
            ['orderInfo.expressFee']: expressFee
        })
        console.log(this.data.orderInfo, '=====');
        this.computedMoney()
            // 调用数字输入框组件的方法更新 sub 和 add 按钮禁用状态
        iptNumberComponent.updated(that.data.orderInfo.quantity)
        if (options.updateAddress) {
            this.setData({ updateAddress: options.updateAddress })
        }
        that.getCouponList()
    },
    // 选择或添加收货地址
    goSelAddress(e) {
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        })
    },
    // 数量改变
    handleQuantityChange(e) {
        console.log(e)
        this.setData({
            ['orderInfo.quantity']: e.detail.value
        })
        this.getCouponList()
    },

    // 选择提货类型
    radioChange(e) {
        let _value = e.detail.value
        if (_value === '1') {
            this.getAddress() // 获取收货地址
        }
        this.setData({
            'orderInfo.goodsType': _value
        })
    },

    // 计算总价
    computedMoney() {
        let that = this
        let { quantity, price, expressFee } = this.data.orderInfo
            // console.log(quantity)
            // 商品总额 = 商品价格 * 数量
            // 实付金额 = 商品总额 - 优惠价格(如果有的话) + 运费
        let _totalMoney = NP.times(quantity, price)
        let _shouldPayMoney = NP.plus(NP.times(quantity, price), expressFee)
        if (!that.data.noAvailableFlag) {
            _shouldPayMoney = NP.minus(_shouldPayMoney, that.data.couponInfo.discountPrice)
            _shouldPayMoney = _shouldPayMoney >= 0 ? _shouldPayMoney : 0
        }
        this.setData({
            totalMoney: (NP.times(quantity, price)).toFixed(2),
            shouldPayMoney: _shouldPayMoney.toFixed(2),
        })
    },
    // 生成订单
    generateOrder() {
        let that = this
        let groupId = app.globalData.groupId
        if (that.data.orderInfo.goodsType === '1' && that.data.deliveryAddressId === '') {
            wx.showToast({
                title: '请添加收货地址',
                icon: 'none'
            })
            return false
        }
        let orderInfo = {...that.data.orderInfo }
        let params = {
            goodsId: orderInfo.goodsId,
            quantity: orderInfo.quantity
        }
        if (that.data.orderInfo.talentId) params.talentId = that.data.orderInfo.talentId
        if (groupId) params.groupId = groupId
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        orderApi.generateOrder(params).then((res) => {
            if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
                that.setData({
                    orderId: res.data.data.orderId
                })
                that.submitOrder(res.data.data.orderId)
            } else {
                wx.hideLoading()
                wx.showToast({
                    icon: 'none',
                    title: res.data.msg
                })
            }
        }).catch((res) => {
            wx.hideLoading()
            wx.showToast({
                icon: 'none',
                title: '网络错误'
            })
        })
    },
    // 提交订单，获取支付参数
    submitOrder(orderId) {
        let that = this
        let params = {
            orderId,
            deliveryAddressId: '',
            userCouponId: that.data.couponInfo.userCouponId || ''
        }
        if (this.data.orderInfo.goodsType === '1') {
            params.deliveryAddressId = that.data.deliveryAddressId
        }
        orderApi.payOrder(params).then((res) => {
            if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
                let payParams = {...res.data.data }
                if (payParams.callWxpayFlag) { // 判断是否需要调起微信支付（完全抵扣掉的商品无需支付）
                    that.pay(payParams)
                } else {
                    // 无需支付也要轮询查取订单状态
                    wx.hideLoading()
                    wx.showLoading({
                        title: '下单中...',
                        mask: true
                    })
                    that.handlePoll()
                }
            } else if (app.globalData.codeConfig.errCode.USER_COUPON_OVERDUE_ERROR === res.data.errCode) {
                wx.hideLoading()
                wx.showToast({
                    icon: 'none',
                    title: '糟糕，优惠券过期了！',
                    duration: 1000
                })
                setTimeout(() => {
                    that.getCouponList()
                }, 500)
            } else {
                wx.showToast({
                    icon: 'none',
                    title: res.data.msg,
                })
                wx.hideLoading()
            }
        }).catch((res) => {
            wx.hideLoading()
            wx.showToast({
                icon: 'none',
                title: '网络错误'
            })
        })
    },
    // 调用微信支付
    pay(payParams) {
        wx.hideLoading()
        let that = this
        wx.requestPayment({
            'timeStamp': payParams.timeStamp,
            'nonceStr': payParams.nonceStr,
            'package': payParams.packageStr,
            'signType': payParams.signType,
            'paySign': payParams.paySign,
            'success': function(res) {
                if (res.errMsg == "requestPayment:ok") {
                    console.log('success')
                    wx.showLoading({
                        title: '查询中...',
                        mask: true
                    })
                    that.handlePoll()
                }
            },
            'fail': function(res) {
                wx.hideLoading()
            },
            'complete': function(res) {}
        })
    },
    // 轮询查询订单状态
    checkOrderStatus() {
        let that = this
        that.setData({
            timeOutLimit: that.data.timeOutLimit += 2
        })
        console.log(`***正在轮询查询状态****timeOutLimit为*** ${that.data.timeOutLimit} ***`)
        orderApi.checkOrderStatus({ orderId: that.data.orderId }).then((res) => {
            console.log(res)
            if (res.data.errCode === app.globalData.codeConfig.errCode.SUCCESS_CODE) {
                let payStatus = res.data.data.payStatus
                let orderType = res.data.data.orderType
                if (payStatus === app.globalData.codeConfig.orderStatus.PAY_SUCC) {
                    clearTimeout(that.data.timerOut)
                    that.setData({
                        timerOut: null
                    })
                    wx.hideLoading()
                    wx.showToast({ title: '支付成功' })
                        // 判断是否为拼团订单，是的话跳转拼团页面
                    if (orderType === app.globalData.codeConfig.orderType.GROUP) {
                        wx.setStorageSync('groupId', '')
                        let groupId = res.data.data.groupId
                        wx.redirectTo({
                            url: `/pages/group/groupDetail?groupId=${groupId}&source=pay`
                        })
                    } else {
                        // 有收货地址跳到已提货宝贝
                        if (that.data.orderInfo.goodsType === '1') {
                            app.globalData.buyGoodsToCouponBag = true
                            wx.switchTab({
                                url: '../couponBag/couponBag'
                            })
                            app.globalData.address.addressId = ''
                            that.setData({
                                deliveryAddressId: ''
                            })
                        } else {
                            that.paySuccDialog()
                        }
                    }
                } else if (payStatus === app.globalData.codeConfig.orderStatus.PAY_FAIL) {
                    clearTimeout(that.data.timerOut)
                    that.setData({
                        timerOut: null
                    })
                    wx.hideLoading()
                    wx.showToast({ title: '支付失败', icon: 'none' })
                } else if (payStatus === app.globalData.codeConfig.orderStatus.ORDER_FAIL) { // 支付成功，下单失败
                    clearTimeout(that.data.timerOut)
                    that.setData({
                        timerOut: null
                    })
                    wx.hideLoading()
                    wx.showModal({
                        title: '下单失败',
                        content: '小布没有抢到货，请在“我的-联系客服”处联系客服申请退款',
                        confirmText: '我知道了',
                        confirmColor: '#FF2424',
                        showCancel: false,
                        success(res) {
                            if (res.confirm) {
                                wx.redirectTo({
                                    url: '../myOrder/myOrder'
                                })
                            }
                        }
                    })
                } else {
                    that.handlePoll()
                }
            } else {
                that.handlePoll()
            }
        }).catch((res) => {
            wx.hideLoading()
            console.log(res)
        })
    },
    // 支付成功弹窗
    paySuccDialog() {
        let that = this
        // let orderInfo = that.data.orderInfo
        $wuxDialog().alert({
            resetOnClose: true,
            title: '付款成功',
            content: '系统正在生成商品券，如您未在“提货券”列表看到该券，请稍等片刻。',
            confirmText: '我知道了',
            onConfirm(e) {
                that.setData({
                    onCancelTip: '可去“提货券-未提货”查看该商品券'
                })
                wx.switchTab({
                    url: '/pages/index/index'
                })
            },
        })
        // $wuxDialog().confirm({
        //     resetOnClose: true,
        //     closable: false,
        //     maskClosable: false,
        //     title: '付款成功',
        //     content: '恭喜您成功购买该商品提货券，是否立即提货？',
        //     confirmText: '立即提货',
        //     cancelText: '暂不提货',
        //     onConfirm(e) {
        //         wx.redirectTo({
        //             url: `/pages/pickUpGoods/pickUpGoods?goodsId=${orderInfo.goodsId}&goodsName=${orderInfo.name}&goodsCount=${orderInfo.quantity}`
        //         })
        //     },
        //     onCancel(e) {
        //         that.setData({
        //             onCancelTip: '可去“提货券-未提货”查看该商品券'
        //         })
        //         wx.switchTab({
        //             url: '/pages/index/index'
        //         })
        //     }
        // })
    },
    // 轮询
    handlePoll() {
        let that = this
        if ((that.data.timeOutLimit - 0) === 0) {
            that.checkOrderStatus()
        }
        if (that.data.timeOutLimit < 20) {
            console.log('调用轮询')
            that.setData({
                timerOut: setTimeout(that.checkOrderStatus, 2000)
            })
        } else {
            console.log(`***停止轮询查询***`)
            wx.showToast({ title: '查询超时', icon: 'none' })
            wx.hideLoading()
            clearTimeout(that.data.timerOut)
            that.setData({
                timerOut: null
            })
        }
    },
    // 处理加号禁用时的点击
    handleDisableAdd() {
        if ((this.data.orderInfo.quantity - 0) === 9999) {
            wx.showToast({ title: '最多购买 9999 个', icon: 'none' })
        } else {
            wx.showToast({ title: '库存不足', icon: 'none' })
        }
    },
    // 超过最大值自动修改
    handleDisableMax() {
        // wx.showToast({title: '库存不足', icon: 'none'})
    },
    // 获取优惠券列表
    getCouponList() {
        let that = this
        wx.showLoading({
            icon: 'none',
            title: '',
            mask: true
        })
        let groupId = app.globalData.groupId || ''
        couponApi.coupon({
            goodsId: that.data.orderInfo.goodsId,
            quantity: that.data.orderInfo.quantity,
            groupId,
            startPage: that.data.page.start + '',
            pageSize: that.data.page.size + ''
        }).then((res) => {
            wx.hideLoading()
            if (res.data.errCode === app.globalData.codeConfig.errCode.SUCCESS_CODE) {
                let couponList = res.data.data.couponList
                if (couponList.length === 0) {
                    that.setData({
                        noAvailableFlag: true
                    })
                } else {
                    let couponInfo = {...couponList[0] }
                    app.globalData.couponInfo = {...couponList[0] }
                    that.setCouponCell(couponInfo)
                    that.setData({
                        noAvailableFlag: false,
                        ['couponInfo']: {...couponInfo }
                    })
                }
                that.computedMoney()
            }
        }).catch((res) => {
            wx.hideLoading()
        })
    },
    // 设置已选择优惠券信息
    setCouponCell({ couponType, discountPrice }) {
        let couponContent = discountPrice + ''
        let couponTypeEnum = {...app.globalData.codeConfig.couponType }
        switch (couponType) {
            case couponTypeEnum.DEDUCT:
                {
                    couponContent = '抵扣券 -￥ ' + couponContent
                    break
                }
            case couponTypeEnum.ASSEMBLE:
                {
                    couponContent = '拼团券 -￥ ' + couponContent
                    break
                }
            case couponTypeEnum.FULL_REDUCTION:
                {
                    couponContent = '满减券 -￥ ' + couponContent
                    break
                }
        }
        this.setData({
            couponContent
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let that = this
        if (app.globalData.isSelectCoupon) {
            if (app.globalData.couponInfo.dontChoose) {
                this.setData({
                    couponInfo: {...app.globalData.couponInfo },
                    dontChoose: true
                })
            } else {
                this.setData({
                    couponInfo: {...app.globalData.couponInfo },
                    dontChoose: false
                })
                this.setCouponCell(that.data.couponInfo)
            }
            this.computedMoney()
            app.globalData.isSelectCoupon = false
				}
				
				// 获取收货地址
        if (app.globalData.address.addressId) {
            this.setData({
                deliveryAddressId: app.globalData.address.addressId,
                deliveryInfo: app.globalData.address,
                haveAddress: true
            })
        } else if (app.globalData.orderInfo.goodsType === '1') {
            this.getAddress() // 获取收货地址
        }
    },
    // 获取收货地址
    getAddress() {
        var that = this
        var params = {
            startPage: '1',
            pageSize: '1'
        }
        deliveryApi.getAddressList(params).then(({ data }) => {
            if (data.errCode === app.globalData.codeConfig.errCode.SUCCESS_CODE) {
                if (data.data.addressList.length > 0) {
                    that.setData({
                        deliveryInfo: data.data.addressList[0],
                        deliveryAddressId: data.data.addressList[0].addressId,
                        haveAddress: true
                    })
                    app.globalData.address = {...data.data.addressList[0] }
                } else {
                    that.setData({
                        deliveryInfo: {},
                        deliveryAddressId: '',
                        haveAddress: false
                    })
                }
            } else {
                console.log(data.msg);
            }
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {
        let that = this
        wx.hideLoading()
        clearTimeout(that.data.timerOut)
        that.setData({
            timerOut: null
        })
        if (that.data.onCancelTip !== '') {
            wx.showToast({
                title: that.data.onCancelTip,
                icon: 'none'
            })
        }
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        let that = this
        wx.hideLoading()
        clearTimeout(that.data.timerOut)
        that.setData({
            timerOut: null
        })
        if (that.data.onCancelTip !== '') {
            wx.showToast({
                title: that.data.onCancelTip,
                icon: 'none'
            })
        }
    }
})